package com.tb.flutter_ad.view;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

public class BannerView implements PlatformView, MethodChannel.MethodCallHandler {
    private View myNativeView;

    BannerView(Activity activity, Context context, BinaryMessenger messenger, int id, Map<String, Object> params) {
        int width = 0;
        int height = 0;
        if (params.containsKey("width")) {
            width = (int) params.get("width");
        }
        if (params.containsKey("height")) {
            height = (int) params.get("height");
        }
        FrameLayout container = new FrameLayout(context);
        container.setLayoutParams(new ViewGroup.LayoutParams(com.ads.admob.utils.DensityUtil.dp2px(context, width), com.ads.admob.utils.DensityUtil.dp2px(context, height)));
        this.myNativeView = container;
        String codeId = (String) params.get("codeId");
        loadBanner(activity, container, codeId, width, height);
        MethodChannel methodChannel = new MethodChannel(messenger, "com.tb.mob/bannerview_" + id);
        methodChannel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        // 在接口的回调方法中可以接收到来自Flutter的调用
    }

    @Override
    public View getView() {
        return myNativeView;
    }

    @Override
    public void dispose() {

    }

    private void loadBanner(Activity context, final FrameLayout container, String codeId, float width, float height) {
        android.util.Log.d("banner____", "loadBanner");
        com.tb.mob.config.TbBannerConfig config = new com.tb.mob.config.TbBannerConfig.Builder()
                .codeId(codeId)//平台申请的代码位id
                .viewWidth((int) width)//期望模板view的width，默认值350（单位dp）
                .viewHight((int) height)//期望模板view的height，默认值0（自适应，单位dp）
                .container(container)//承载视图的容器
                .build();
        com.tb.mob.TbManager.loadBanner(config, context, new com.tb.mob.TbManager.BannerLoadListener() {
            @Override
            public void onFail(String s) {
                //加载失败
                android.util.Log.d("banner____", "onFail=" + s);
                Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDismiss() {
                //关闭
            }

            @Override
            public void onClicked() {

            }

            @Override
            public void onExposure(com.tb.mob.bean.Position position) {
                android.util.Log.d("banner____", "onExposure");
            }
        });
    }
}
